<template>
  <div style="padding:30px;">
    <el-row :gutter="20" style="margin-bottom:10px;">
      <el-col :span="24">
      <div class="demonstration" style="margin-bottom: 15px;">    
         <input title="请选择文件" value="请选择文件" type="file" class="file"> 
         <el-button @click="fileUpload1"  type="primary" size="mini" style="margin:30px auto;">导入</el-button>
        <el-button @click="download" type="primary" size="mini" style="margin:30px auto;">下载模板</el-button>
      </div>
      </el-col>
    </el-row>
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column align="center" label="ID" width="80" prop="id">
        <!-- <template slot-scope="scope">
        <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>-->
      </el-table-column>
       <el-table-column align="center" label="客户公司" prop="companyName"></el-table-column>
      <el-table-column align="center" label="合同编号" prop="conNumber"></el-table-column>
      <el-table-column align="center" label="合同文本" prop="conText"></el-table-column>
      <el-table-column align="center" label="联系人" prop="relPersonName"></el-table-column>
      <!-- <el-table-column align="center" label="电话" prop="telephone"></el-table-column> -->
     
      
      <el-table-column align="center" label="考核金额" prop="cheMoney"></el-table-column>
      <el-table-column align="center" label="签约日期" prop="signTime"></el-table-column>
      <el-table-column align="center" label="完成日期" prop="finishTime"></el-table-column>
      <el-table-column align="center" label="签约人" prop="signPersonName"></el-table-column>
      <el-table-column align="center" label="预收款" prop="advReceived"></el-table-column>
      <el-table-column align="center" label="执行日期" prop="executeTime"></el-table-column>
      <el-table-column align="center" label="操作" width="210">
        <template slot-scope="scope">
          <el-button size="mini"  type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button v-if="rolee=='2'" size="mini" style="margin-top:5px" type="warning" @click="tjsk(scope.$index, scope.row)">添加收款</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label="分子公司">
          <el-select v-model="value1" placeholder="请选择分子公司" @change="findBumen()">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="value2" placeholder="请选择部门" @change="findPerson()">
            <el-option v-for="item in options2" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人">
          <el-select v-model="value3" filterable placeholder="请选择">
            <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属项目：">
    
        </el-form-item>
         <div v-for="o in ruleForm.items" :key="o" class="text item">
               {{'项目编号：' + o.id +'&emsp;&emsp;项目名称：'+o.proName }}
           </div>
           <el-form-item label="客户公司" prop="companyName">
          <el-input v-model="ruleForm.companyName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="合同编号" prop="conNumber">
          <el-input v-model="ruleForm.conNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="合同文本" prop="conText">
          <el-input type="textarea" v-model="ruleForm.conText" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="ruleForm.telephone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="考核金额" prop="cheMoney">
          <el-input-number v-model="ruleForm.cheMoney" :precision="2" :step="0.1" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="签约人">
          <el-select v-model="value4" filterable placeholder="请选择">
            <el-option
              v-for="item in options4"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签约日期" prop="signTime">
          <el-date-picker v-model="ruleForm.signTime" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="完成日期" prop="finishTime">
          <el-date-picker v-model="ruleForm.finishTime" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="预收款" prop="advReceived">
          <el-input-number v-model="ruleForm.advReceived" :precision="2" :step="0.1" :min="1"></el-input-number>
        </el-form-item> -->
        <el-form-item label="执行日期" prop="executeTime">
          <el-date-picker v-model="ruleForm.executeTime" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="收款进度" prop="rate">
          <el-input-number v-model="ruleForm.rate" :precision="0" :step="1" :min="0" :max="100"></el-input-number>&emsp;%
        </el-form-item> -->
        <el-form-item label="合同款" prop="amount">
          <el-input-number v-model="ruleForm.amount" :precision="2" :step="0.1" :min="1"></el-input-number>&emsp;¥
        </el-form-item>
        <el-form-item label="合同图片">
          <el-upload
            class="upload-demo"
            :action="host+'upload'"
            :headers="{token:getToken()}"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :on-success="handleSuccess"
            accept="image/*"
          >
            <el-button size="small">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <v-pagination
      style="margin-top:20px"
      @page-change="pageChange"
      @page-size-change="pageSizeChange"
      :total="total"
      :page-size="pageSize"
      :layout="['total', 'prev', 'pager', 'next', 'sizer', 'jumper']"
    ></v-pagination>
  </div>
</template>

<!-- 引入组件库 -->
<script>
import { getToken, gettype, getid,  getlevel, getrole } from "@/utils/auth";
import request from "@/utils/request";
import moment from "moment";
import { MessageBox, Message } from "element-ui";
import { host } from "@/config";
var formData = new FormData(); // 声明一个FormData对象
var formData = new window.FormData();
export default {
  name: "contractlist",
  data() {
    return {

      rolee:getrole(),
      host: host,
      info: null,
      getid,
      getToken,
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      total: 1,

      tableData: [],
      dialogTitle: "",
      dialogTableVisible: false,
      dialogFormVisible: false,
      editId: 0,
      ruleForm: {
        companyName:null,
        conNumber: null,
        conText: null,
        relPerson: null,
        telephone: null,
        cheMoney: null,
        signTime: null,
        finishTime: null,
        advReceived: null,
        executeTime: null,
        rate: null,
        amount: null
      },
      rules: {
        conNumber: [{ required: true, message: "请输入", trigger: "blur" }]
      },
      value1: null,
      options1: [],
      value2: null,
      options2: [],
      value3: null,
      options3: [],
      value4: null,
      options4: [],
      value5: 0,
      options5: [],
      value6: -1,
      optionsxm:[],
      fileList: [
        // {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, //// {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
      ]
    };
  },
  created() {
    this.findInfo();
    setTimeout(() => {
      this.findList();
      this.findCompnany();
    }, 500);
  },
  methods: {
    findPerson(query) {
      let self = this;
      var resdata = {
        pid: this.value2,
        name: query
      };
      request("/person/selectComboBox", {
        method: "get",
        headers: {
          "Content-Type": "application/json"
        },
        params: resdata
      }).then(function(response) {
        let list = response.data.object.map(item => {
          return { value: `${item.id}`, label: `${item.name}` };
        });
        self.options3 = list;
        self.options4 = list;
      });
    },
    findBumen() {
      let self = this;
      var resdata = {
        bid: this.value1,
        page: this.pageIndex,
        pageSize: 1000
      };
      request("/department/selectComboBox", {
        method: "get",
        headers: {
          "Content-Type": "application/json"
        },
        params: resdata
      }).then(function(response) {
        self.options2 = response.data.object;
      });
    },
    findCompnany() {
      let self = this;
      var resdata = {
        cid: self.info.cid,
        page: this.pageIndex,
        pageSize: 1000
      };
      request("/branch/select", {
        method: "get",
        headers: {
          "Content-Type": "application/json"
        },
        params: resdata
      }).then(function(response) {
        self.options1 = response.data.object;
        self.options5 = response.data.object;
      });
    },
    findInfo() {
      let self = this;
      request("/person/rolelist", {
        method: "get",
        headers: {
          "Content-Type": "application/json"
        }
      }).then(function(response) {
        self.info = response.data.object;
      });
    },
    remoteMethod(query) {
      if (query !== "") {
        this.selectLoading = true;
        this.findPerson(query);
      } else {
        this.options = [];
      }
    },
    findList() {
      let self = this;
      var resdata = {
        // id:this.info.cid,
        page: this.pageIndex,
        pageSize: this.pageSize
      };
      if (this.value5 != 0) {
        resdata.uid = this.value5;
      }
      if (this.value6 != -1) {
        resdata.flag = this.value6;
      }
      // 模拟后台接口
      this.loading = true;
      request("contract/select", {
        method: "get",
        headers: {
          "Content-Type": "application/json"
        },
        params: resdata
      }).then(function(response) {
        console.log(response.data);
        self.tableData = response.data.object;
        self.total = response.data.total;
      });
    },
    // 编辑的操作
    handleEdit(index, row) {
      this.dialogTitle = "编辑合同";
      this.dialogFormVisible = true;
      this.editId = row.id;
      this.findDetail(row.id);
      console.log(index, row);
    },



    tjsk(index, row) {
     
      this.editId = row.id;

       this.$router.push({
                path: '/tjsk',
                query: {
                  id: row.conNumber,
               
                }
              })


    },
    findDetail(id) {
      let self = this;
      request("/contract/find/" + id, {
        method: "get",
        headers: {
          "Content-Type": "application/json"
        }
      }).then(function(response) {
        let res = response.data.object;
        let ruleForm = {
          companyName:res.companyName,
          conNumber: res.conNumber,
          conText: res.conText,
          telephone: res.telephone,
          cheMoney: res.cheMoney,
          signTime: res.signTime,
          finishTime: res.finishTime,
          advReceived: res.advReceived,
          executeTime: res.executeTime,
          rate: res.rate,
          amount: res.amount,
          items:res.items
        };
        self.ruleForm = ruleForm;
        self.value1 = res.uid;
        self.findBumen(res.pid);
        self.value2 = res.pid;
        self.findPerson();
        self.value3 = res.relPerson;
        self.value4 = res.signPerson;

        self.fileList = res.contentlist.map(item => {
          return { name: item, url: item };
        });
        self.fileListTmp = res.contentlist.map(item => {
          return item;
        });
      });
    },
    // 删除的操作
    handleDelete(index, row) {
      let self = this;
      console.log(index, row);
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          request("/contract/del/" + row.id, {
            headers: {
              method: "get",
              "Content-Type": "application/json"
            }
          }).then(function(response) {
            if (response.data.code == 1) {
              Message({
                message: "删除成功",
                type: "success",
                duration: 2 * 1000
              });
              self.findList();
            }
          });
        })
        .catch(() => {
          Message({
            message: "已取消删除",
            type: "info",
            duration: 2 * 1000
          });
        });
    },

    pageChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.findList();
    },
    pageSizeChange(pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.findList();
    },
        fileUpload() {
      var _this = this;
      var formData = new window.FormData();
      // formData.append("uploadFile", $("input[name='uploadFile']")[0].files[0]);
      formData.append("file", this.files, this.fileName);
      console.log(formData);
      _this.formData = formData;
    },
    // 模板下载
    download() {
      window.location.href = this.$host + "/downloadtemplate?filename=1.xlsx";
    },
    fileUpload1(a) {
      var _this = this;
      formData.append(
        "file",
        document.querySelector("input[type=file]").files[0]
      ); // 'file' 这个名字要和后台获取文件的名字一样;

      request("/contract/import", {
        method: "post",
        headers: { "Content-Type": "multipart/form-data" },
        data: formData
      })
        .then(function(response) {
          console.log(response);
          alert(response.data.message);
        })
        .catch(function(reason) {});
    },
    submitForm(formName) {
      let self = this;
      let resdata = this.ruleForm;
      let params = {
        id: this.editId,
        cid: this.info.cid,
        uid: this.value1,
        pid: this.value2,
        relPerson: this.value3 * 1,
        // flag: 1,
        conNumber: resdata.conNumber,
        conText: resdata.conText,
        telephone: resdata.telephone,
        cheMoney: resdata.cheMoney,
        sign_person: this.value4 * 1,
        signTime: moment(resdata.signTime).format("YYYY-MM-DD HH:mm:ss"),
        finishTime: moment(resdata.finishTime).format("YYYY-MM-DD HH:mm:ss"),
        advReceived: resdata.advReceived,
        executeTime: moment(resdata.executeTime).format("YYYY-MM-DD HH:mm:ss"),
        rate: resdata.rate,
        amount: resdata.amount,
        context: ""
      };
      for (let i in this.fileListTmp) {
        let url = this.fileListTmp[i];
        params.context += params.context == "" ? url : "," + url;
      }
      console.log(params);
      this.$refs[formName].validate(valid => {
        if (valid) {
          request("contract/update", {
            method: "post",
            headers: {
              "Content-Type": "application/json"
            },
            data: params
          }).then(function(response) {
            console.log(response.data);
            self.dialogFormVisible = false;
            if (response.data.code == 1) {
              Message({
                message: "修改成功",
                type: "success",
                duration: 2 * 1000
              });
            }
          });
        } else {
          console.log("修改失败");
          return false;
        }
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
      window.open(host + "download?fileurl=" + file.url);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response, file, fileList) {
      console.log("3", fileList);
      if (response.code == 1) {
        this.fileListTmp = fileList.map(item => {
          if (item.response) {
            return item.response.object;
          } else {
            return item.url;
          }
        });
      } else {
        Message({
          message: "上传失败",
          type: "error",
          duration: 2 * 1000
        });
      }
    }
  }
};
</script>
